package com.elawlink.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 文件工具类
 */
public class FileUtil {
	
	/**
     * 获取目录下面文件列表，最后修改时间大于60秒以上,如何没有文件，返回[]
     * @param pathname
     */
    public static List<String> getFileListNotEmpty(List<String> list,String path) {
    	//先将指定路径下的所有文件实例化
        File file = new File(path);
        //判断实例化的对象file是否存在，即指定路径是否存在
        if (file.exists()) {
            //则将所有文件的实例化对象转化为数组形式
            File[] files = file.listFiles();
            //遍历文件数组
            for (File file2 : files) {
                //如果是拿出来的File是文件夹类型，就调用自己，利用递归的思想，即一层一层地打开
                if (file2.isDirectory()) {
                	list.add(file2.getPath());
                    //调用自己时候传入的参数为上一句判断出来的文件夹路径
                	getFileListNotEmpty(list,file2.getAbsolutePath());
                }else{
                	if(file2.length() > 0){
	                	long now = System.currentTimeMillis();
	                	long lastModified = file2.lastModified();
	                	if(now - lastModified > 10000){ //最后修改时间大于10秒才加入
	                		list.add(file2.getPath());
	                	}
                	}
                }
            }
        }
        boolean flag = true;
        for(String filePath : list){
        	if(filePath.contains(".")){
        		flag = false;
        		break;
        	}
        }
        if(flag){
        	return new ArrayList<String>();
        }
        return list;
    }
	
    /**
     * 获取目录下面 文件列表
     *
     * @param pathname
     */
    public static List<String> getFileList(List<String> list,String path) {
        //先将指定路径下的所有文件实例化
        File file = new File(path);
        //判断实例化的对象file是否存在，即指定路径是否存在
        if (file.exists()) {
            //则将所有文件的实例化对象转化为数组形式
            File[] files = file.listFiles();
            //遍历文件数组
            for (File file2 : files) {
                //如果从数组中拿出来的值是File是文件类型，就直接先打印这个文件的路径名称
                list.add(file2.getPath());
                //如果是拿出来的File是文件夹类型，就调用自己，利用递归的思想，即一层一层地打开
                if (file2.isDirectory()) {
                    //调用自己时候传入的参数为上一句判断出来的文件夹路径
                    getFileList(list,file2.getAbsolutePath());
                }
            }
        }
        return list;
    }
    
    
    /**
     * 获取文件修改时间 
     * @param filePathName
     * @return
     */
    public static String getUpdateTime(String filePathName) {
        File file = new File(filePathName);
        Calendar cal = Calendar.getInstance();
        long time = file.lastModified();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cal.setTimeInMillis(time);
        return formatter.format(cal.getTime());
    }

    /**
     * 删除指定的文件
     *
     * @param filePathName
     * @return
     */
    public static void delete(String filePathName) {
        File file = new File(filePathName);
        file.delete();
    }

    /**
     * 重命名
     * @param oldFileNamem
     * @param newFileNamem
     */
    public static void rename(String oldFileNamem,String newFileNamem) {
    	//想命名的原文件的路径  
        File file = new File(oldFileNamem);  
        file.renameTo(new File(newFileNamem));  
    }
    
    /**
     * 复制文件
     * @param oldFileNamem
     * @param newFileNamem
     */
    public static void copy(String oldFileNamem,String newFileNamem) {
        try {
			copyFileUsingFileStreams(new File(oldFileNamem), new File(newFileNamem));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    /**
     * 复制文件
     * @param source
     * @param dest
     * @throws IOException
     */
    public static synchronized void copyFileUsingFileStreams(File source, File dest)
            throws IOException {    
        InputStream input = null;    
        OutputStream output = null;    
        try {
               input = new FileInputStream(source);
               output = new FileOutputStream(dest);        
               byte[] buf = new byte[1024];        
               int bytesRead;        
               while ((bytesRead = input.read(buf)) != -1) {
                   output.write(buf, 0, bytesRead);
               }
        } finally {
            input.close();
            output.close();
        }
    }
    
    /**
     * 复制文件不关闭流
     * @param source
     * @param dest
     * @throws IOException
     */
    public static synchronized void copyFileNotClose(File source, File dest)
            throws IOException {    
        InputStream input = null;    
        OutputStream output = null;    
        try {
               input = new FileInputStream(source);
               output = new FileOutputStream(dest);        
               byte[] buf = new byte[1024];        
               int bytesRead;        
               while ((bytesRead = input.read(buf)) != -1) {
                   output.write(buf, 0, bytesRead);
               }
        } finally {
//            input.close();
//            output.close();
        }
    }

    
    /**
     * 获取url文件文件名称
     * @param filePathName
     * @return
     */
    public static String getFileNameByUrl(String filePathName) {
        String[] str = filePathName.split("\\/");
        if (str.length == 1) {
        	str = filePathName.split("\\\\");
        	if (str.length == 1) {
        		return filePathName;
        	}
        }
        String name = str[str.length - 1];
        return name.split("\\?")[0];
    }
    
    /**
     * 获取url文件目录
     * @param filePathName
     * @return
     */
    public static String getFilePathByUrl(String filePathName) {
    	return filePathName.replaceAll(getFileNameByUrl(filePathName), "");
    }
    
    /**
     * 获取url文件后缀
     * @param filePathName
     * @return
     */
    public static String getFileTypeByUrl(String url) {
        String[] str = url.split("\\.");
        return str[str.length - 1];
    }
    
    
    /**
     * 获取url文件文件名称-不去掉后面符号
     *
     * @param filePathName
     * @return
     */
    public static String getFileNameByUrlAll(String filePathName) {
    	String[] str = filePathName.split("\\/");
    	if (str.length == 1) {
    		str = filePathName.split("\\\\");
    		if (str.length == 1) {
    			return filePathName;
    		}
    	}
    	String name = str[str.length - 1];
    	return name.replaceAll("\\?", "_").replaceAll("\\=", "_");
    }

    /**
     * 自动加上utf-8编码
     *
     * @param fileName
     * @param content
     */
    public static String writeToFile(boolean utf8,String saveFilePath, String fileName, String content, boolean append) {
    	if(utf8){
    		String first = "<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title></title></head><body>";
    		String last = "</body></html>";
    		content = first + content + last;
    	}
    	return writeToFile(saveFilePath, fileName, content, append);
    }
    

    /**
     * 追加文件：使用FileWriter
     *
     * @param fileName
     * @param content
     */
    public static String writeToFile(String saveFilePath, String fileName, String content, boolean append) {
        FileWriter writer = null;
        try {
            if (!append) {
                File deleteFile = new File(saveFilePath + fileName);
                if (deleteFile.exists()) {
                    deleteFile.delete();
                }
            }

            File file = new File(saveFilePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            writer = new FileWriter(saveFilePath + fileName, append);
            
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File file = new File(fileName);
        file.setExecutable(false);//设置可执行权限
        file.setReadable(true, false);//设置可读权限
        file.setWritable(true);
        return saveFilePath + fileName;
    }

    /**
     * 查看指定文件是否存在
     *
     * @param string
     * @param string2
     * @return
     */
    public static boolean fileIsExist(String saveFileDir, String fileName) {
        if (!saveFileDir.endsWith("/") && !saveFileDir.endsWith("\\")) {
            saveFileDir = saveFileDir + "/";
        }
        File file = new File(saveFileDir + fileName);
        
        boolean exist = file.exists();
        if(exist && file.length() == 0 && file.isFile()){ //如果文件大小为0，则删除文件 返回false
        	file.delete(); 
        	exist = false;
    	}
        
        return exist;
    }

    /**
     * 查看指定文件是否存在
     * @param string
     * @param string2
     * @return
     */
    public static boolean fileIsExist(String filePath) {
        File file = new File(filePath);
        
        boolean exist = file.exists();
        if(exist && file.length() == 0 && file.isFile()){ //如果文件大小为0，则删除文件 返回false
        	file.delete(); 
        	exist = false;
    	}
        
        return exist;
    }

    
    /** 
     * 文本文件转换为指定编码的字符串 
     * @param file         文本文件 
     * @param encoding 编码类型 
     * @return 转换后的字符串 
     * @throws IOException 
     */ 
    public static String file2String(File file) { 
        InputStreamReader reader = null; 
        StringWriter writer = new StringWriter(); 
        try { 
                reader = new InputStreamReader(new FileInputStream(file), "UTF-8"); 
                //将输入流写入输出流 
                char[] buffer = new char[1024]; 
                int n = 0; 
                while (-1 != (n = reader.read(buffer))) { 
                        writer.write(buffer, 0, n); 
                } 
        } catch (Exception e) { 
                e.printStackTrace(); 
                return null; 
        } finally { 
                if (reader != null) 
                        try { 
                                reader.close(); 
                        } catch (IOException e) { 
                                e.printStackTrace(); 
                        } 
        } 
        //返回转换结果 
        if (writer != null) 
                return writer.toString(); 
        else return null; 
    }
    
    /**
     * 获取文件长度,返回kb
     * @param file
     */
    public static String getFileSizeKB(File file) {
        if (file.exists() && file.isFile()) {
            String fileName = file.getName();
            Long kbSize = file.length()/1024;
            return String.valueOf(kbSize.intValue());
        }
        return null;
    }
    
    /**
     * 读出文件内容为字符串
     */
     public static String readFileStr(String filePath) {
	      File file = new File(filePath);
	      FileInputStream is = null;
	      StringBuilder stringBuilder = null;
	      try {
		       if (file.length() != 0) {
			        /**
			         * 文件有内容才去读文件
			         */
			        is = new FileInputStream(file);
			        InputStreamReader streamReader = new InputStreamReader(is);
			        BufferedReader reader = new BufferedReader(streamReader);
			        String line;
			        stringBuilder = new StringBuilder();
			        while ((line = reader.readLine()) != null) {
			         // stringBuilder.append(line);
			         stringBuilder.append(line+"\n");
			        }
			        reader.close();
			        is.close();
		       }
	      } catch (Exception e) {
	    	  e.printStackTrace();
	      }
	      return String.valueOf(stringBuilder);
	     
	}
     
     /**
      * 读出文件内容为字符串
      */
    public static boolean writeFileStr(String filePath,String content) {
	    FileOutputStream fos;
  		try {
  			fos = new FileOutputStream(filePath,true);
  			fos.write(content.getBytes());
  	        fos.close();
  		} catch (Exception e) {
  			e.printStackTrace();
  			return false;
  		}
 	    return true;
 	}

	public static void main(String[] args) throws IOException {
//		System.out.println(getFilePathByUrl("/mnt/grab/equitydetail/old/cn/CS20170907000110_2017-09-05.html"));
//		copy("D:\\JTT808.pdf", "D:\\JTT808_bak.pdf");
//		copyFileUsingFileStreams(new File("D:\\JTT808.html"),new File("D:\\JTT808_NEW.html"));
//		System.out.println(getUpdateTime("D:\\JTT808.pdf"));
//		System.out.println(getFileTypeByUrl("D:\\JTT808.html"));
//		System.out.println(file2String(new File("D:\\JTT808.html")));
//		System.out.println(getFileNameByUrlAll("https://www.sfc.hk/edistributionWeb/gateway/TC/news-and-announcements/news/enforcement-news/doc?refNo=20PR3"));
//		System.out.println(getFileNameByUrl("https://www.hkex.com.hk/News/News-Release/1999-SEHK/991010?sc_lang=zh-HK"));
		System.out.println(file2String(new File("E://调试1.html")));
	}
    
}



